package com.yy.main.app.springsession;

import com.yy.constant.AppConstant;
import com.yy.kit.log.YYLogKits;
import com.yy.pojo.base.TUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * session拦截器，判断用户是否登陆
 * </p>
 *
 * @author 杨阳
 * @since 2017年9月1日14:54:54
 */
public class SessionInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        YYLogKits.info(SessionInterceptor.class, "┌───────────────────────────────────────────────────────────────────────────┐");
        YYLogKits.info(SessionInterceptor.class, "├用户会话拦截器，用户请求URI:{} ", request.getRequestURI());
        YYLogKits.info(SessionInterceptor.class, "├用户会话拦截器，用户请求URL:{} ", request.getRequestURL());
        String uri = request.getRequestURI();
        if (uri.equals(AppConstant.PRO_ROO_PATH)
                || uri.equals(AppConstant.PRO_LOGIN_PATH)
                || uri.equals(AppConstant.PRO_WEBJARS_PATH)
                || uri.indexOf("/error") > -1) {
            // 去登陆页面、用户登录操作，WEBJAR路径，错误路径，放过检查
            YYLogKits.info(SessionInterceptor.class, "├进入首页或者用户登陆，放过检查....");
            YYLogKits.info(SessionInterceptor.class, "└───────────────────────────────────────────────────────────────────────────┘");
            return true;
        }
        HttpSession session = request.getSession();
        TUser user = (TUser) session.getAttribute(AppConstant.SESSION_KEY);
        if (null == user) {
            YYLogKits.info(SessionInterceptor.class, "├session失效，跳转到登陆页面....");
            YYLogKits.info(SessionInterceptor.class, "└───────────────────────────────────────────────────────────────────────────┘");
            response.sendRedirect("/");
            return false;
        } else {
            YYLogKits.info(SessionInterceptor.class, "├用户正常登陆，放过检查....");
            YYLogKits.info(SessionInterceptor.class, "└───────────────────────────────────────────────────────────────────────────┘");
            return true;
        }
    }

}
